/*
  prerequest:
    $ sudo yum install -y mysql-devel  

  Installed:
  mariadb-devel.x86_64 1:5.5.64-1.el7
  /usr/include/mysql/mysql.h
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<mysql.h>
#include"mysqldb.h"
#include"cJSON.h"

MYSQL *mysql = NULL;

int mydb_open(struct __mydb_conn_info* conn)
{
  if (mysql_library_init(0, NULL, NULL)) {
    fprintf(stderr, "could not initialize MySQL client library\n");
    exit(1);
  }
 
  mysql = mysql_init(mysql);

  if (!mysql) {
    puts("Init faild, out of memory?");
    return EXIT_FAILURE;
  }
  
  /* 查询内容如果包含了中文，
  必须在连接数据库之前，设置好字符编码格式为utf8 */
  mysql_options(mysql, MYSQL_SET_CHARSET_NAME, "utf8"); 
  mysql_options(mysql, MYSQL_INIT_COMMAND, "SET NAMES utf8"); 
  mysql_options(mysql, MYSQL_READ_DEFAULT_FILE, (void *)"./my.cnf");

  if (!mysql_real_connect(mysql,       /* MYSQL structure to use */
			  conn->host,         /* server hostname or IP address */ 
			  conn->user,         /* mysql user */
			  conn->pass,          /* password */
			  conn->db,               /* default database to use, NULL for none */
			  conn->port,           /* port number, 0 for default */
			  conn->sockpipe,        /* socket file or named pipe name */
			  conn->flag /* connection flags */ )) {
    puts("Connect failed\n");
  } else {
    puts("Connect OK\n");
  }
        
  return EXIT_SUCCESS;
}

int mydb_exit(void)
{
  mysql_close(mysql);
  mysql_library_end();
  mysql = NULL;
  return 0;
}

int fetch_field_data(void)
{
  MYSQL_RES *result = mysql_store_result(mysql);
  MYSQL_ROW row;

  if (!result) {
    printf("Couldn't get results set: %s\n", mysql_error(mysql));
  } else {
    unsigned int i, num_fields = mysql_num_fields(result);
    for (i = 0; i < num_fields; i++){
        MYSQL_FIELD *field = mysql_fetch_field_direct(result, i);
        printf("%s ",  field->name);
    }printf("\n");
    while ((row=mysql_fetch_row(result)) != NULL){ //获取整条数据内容
      for (i = 0; i < num_fields; i++){
          if (NULL == row[i]){
              printf("NULL\n");
          }else{
              printf("%s ", row[i]);
          }   
      }printf("\n");
    }
    mysql_free_result(result);

  }

  return 0;
}

int fetch_field_data_to_json(struct __user_query_session* uqueryses)
{
  MYSQL_RES *result = mysql_store_result(mysql);
  MYSQL_ROW row;
  char* fieldNames[100];
  if(uqueryses->json == NULL)
    return 1;
  if (!result) {
    printf("Couldn't get results set: %s\n", mysql_error(mysql));
  } else {
    unsigned int i, num_fields = mysql_num_fields(result);
    for (i = 0; i < num_fields; i++){
        MYSQL_FIELD *field = mysql_fetch_field_direct(result, i);
        //printf("%s ",  field->name);
        fieldNames[i] = field->name;

    }//printf("\n");
    while ((row=mysql_fetch_row(result)) != NULL){ //获取整条数据内容
      cJSON* item = cJSON_CreateObject();
      for (i = 0; i < num_fields; i++){
          if (NULL == row[i]){
              //printf("NULL\n");
          }else{
              //printf("%s ", row[i]);
            cJSON_AddStringToObject(item, fieldNames[i], row[i]);            
          }   
      }//printf("\n");
      cJSON_AddItemToArray(uqueryses->json, item);
    }
    mysql_free_result(result);

  }

  uqueryses->string = cJSON_Print(uqueryses->json); 
  printf("%s\n", uqueryses->string);
  
  return 0;
}

int mydb_query(const char* query, struct __user_query_session* uqueryses)
{
    if (mysql_real_query(mysql, query, strlen(query))) {
      printf("Query failed: %s\n", mysql_error(mysql));
    } else {
      puts("Query OK");
      if((strncmp(query, "select", 6) == 0 || strncmp(query, "SELECT", 6) == 0) && uqueryses == NULL ){
        fetch_field_data();
      }
      else if(strncmp(query, "insert", 6) == 0 || strncmp(query, "INSERT", 6) == 0){

      }
      else if(strncmp(query, "select", 6) == 0 && uqueryses != NULL)
      {
        fetch_field_data_to_json(uqueryses);
      }
    }

    return 0;

}